package com.sunny.ihealth.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.sunny.ihealth.BaseService;
import com.sunny.ihealth.R;
import com.sunny.ihealth.data.LocalData;
import com.sunny.ihealth.entity.eventbus.RunDateEvent;
import com.sunny.ihealth.entity.eventbus.SportDataChangeEvent;
import com.sunny.ihealth.entity.eventbus.UserChangeEvent;
import com.sunny.ihealth.ui.activity.InviteActivity;
import com.sunny.ihealth.ui.activity.SplashActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

/**
 * 提供计步功能
 * Created by Sunny  An on 2016/6/5.
 */
public class CoreService extends BaseService implements StepCounter.OnStepChangedListener, SleepTimeMonitor.OnSleepTimeChangedListener {

    private static final String TAG = "TAG::WalkService";
    private static final int STEP_CACHE_SIZE = 50;
    private static final int NOTIFICATION_ID = 0x999;

    //计步
    private StepCounter stepCounter;
    //因为Step Sensor Counter 是从开机计数的，所以要有一个基值
    private int baseStep = 0;
    private int step = 0;
    //睡眠监测
    private SleepTimeMonitor sleepTimeMonitor;
    //通知
    private NotificationCompat.Builder builder;
    public static Notification notification;
    private NotificationManager notificationManager;

    private int walk = 0;
    private int sleep = 0;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        EventBus.getDefault().register(this);
        super.onCreate();
        Log.e(TAG, "onCreate");
        stepCounter = new StepCounter(getApplicationContext());
        if (!stepCounter.register()) {
            Toast.makeText(getApplicationContext(), "您的设备不支持计步功能...", Toast.LENGTH_SHORT).show();
            //return;
        }
        stepCounter.setListener(this);

        sleepTimeMonitor = new SleepTimeMonitor(getApplicationContext());
        sleepTimeMonitor.register();
        sleepTimeMonitor.setOnSleepTimeChangedListener(this);

        initNotification();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        stepCounter.unRegister();
        sleepTimeMonitor.unRegister();
        stepCounter = null;
        sleepTimeMonitor = null;
        saveStep(getCurrentUser());
        Log.e(TAG, "onDestroy");
        notificationManager.cancel(NOTIFICATION_ID);
        stopForeground(true);
        System.exit(0);
    }

    private void initNotification() {
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, SplashActivity.class), 0);
        builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
               // .setSmallIcon(R.drawable.ic_notify)
                .setSmallIcon(R.mipmap.ic_launcher, 0)
                .setAutoCancel(false)
                .setContentTitle("今天的运动状态")
                .setContentText("")
                .setContentIntent(pendingIntent)
                .setOngoing(true);
        notification = builder.build();
        notificationManager.notify(NOTIFICATION_ID, notification);
        startForeground(NOTIFICATION_ID, notification);
    }

    private void setTitle(int step) {
        builder.setContentText("您今天走了" + step + "步");
        notification = builder.build();
        notificationManager.notify(NOTIFICATION_ID, notification);
        startForeground(NOTIFICATION_ID, notification);
    }

    /**
     * 监听用户状态改变
     */
    @Subscribe
    public void onUserChanged(UserChangeEvent event) {
        //保存老用户数据
        saveStep(event.getOldUsername());
    }

    private void saveStep(String username) {
        //保存用户数据
        LocalData.saveWalkStep(username, step);
        //重新计数
        baseStep = 0;

        walk = LocalData.getTodaySportData(getCurrentUser()).getWalk();
        setTitle(walk);
    }

    @Override
    public void onStepChanged(int totalStep) {
        if (baseStep == 0) {
            baseStep = totalStep - 1;
        }
        step = totalStep - baseStep;
        SportDataChangeEvent event = new SportDataChangeEvent();
        event.setType(SportDataChangeEvent.Type.WALK);

        if (step >= STEP_CACHE_SIZE) {
            saveStep(getCurrentUser());
        } else {
            event.setStepCache(step);
            setTitle(walk + step);
        }
        EventBus.getDefault().post(event);
    }

    @Override
    public void onSleepTimeChanged(int sleepTime) {
        LocalData.saveSleepTime(getCurrentUser(), sleepTime);
        SportDataChangeEvent event = new SportDataChangeEvent();
        event.setType(SportDataChangeEvent.Type.SLEEP);
        EventBus.getDefault().post(event);
    }


    @Subscribe
    public void onRunDateReceive(RunDateEvent event) {
        if (getCurrentUser() == null) {
            return;
        }
        Intent intent = new Intent(this, InviteActivity.class);
        intent.putExtra("data", event.getBmobIMUserInfo());
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification n = new Notification.Builder(this)
                .setSmallIcon(R.drawable.ic_notify)
                .setAutoCancel(false)
                .setContentTitle("您收到一条邀请")
                .setContentText(event.getBmobIMUserInfo().getName() + "邀请您一起跑步")
                .setContentIntent(pendingIntent)
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true)
                .setVibrate(new long[]{200, 200, 200, 200, 200, 200})
                .build();
        notificationManager.notify(0x111, n);
    }
}
